// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.

import Vue from 'vue';
import router from '@/router/index';
import axios from 'axios';
import store from '@/store/index';


// 格式化param
function toFormData(obj) {
  var query = '';
  var name, value, fullSubName, subName, subValue, innerObj, i;

  for (name in obj) {
    value = obj[name];

    if (value instanceof Array) {
      for (i = 0; i < value.length; ++i) {
        console.log(name);
        subValue = value[i];
        fullSubName = name;
        innerObj = {};
        innerObj[fullSubName] = subValue;
        query += toFormData(innerObj) + '&';
      }
    } else if (value instanceof Object) {
      for (subName in value) {
        subValue = value[subName];
        fullSubName = name + '[' + subName + ']';
        innerObj = {};
        innerObj[fullSubName] = subValue;
        query += toFormData(innerObj) + '&';
      }
    } else if (value !== undefined && value !== null) {
      query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }
  }
  return query.length ? query.substr(0, query.length - 1) : query;
}
// 弹出提示框
function showMsg(msgType, msg) {
  if (msg === '' || msg === null || msg === undefined) {
    return null;
  } else {
    switch (msgType) {
      case 'error': break;
      case 'success': break;
      default: break;
    }
  }
}
// 处理错误
function errorSwich(err, type) {
  let routePath = router.history.current.path;
  let status = err.code;
  let msg = err.message;
  switch (status) {
    case 300:
      // goPage(status);
      if (routePath != '/') {
        router.push({
          path: '/',
          query: { redirect: routePath }
        });
        showMsg('error', msg);
      }
      break;
    case 401:
      store.commit('setUserInfo', {});
      logout();
      break;
    case 403:
      goPage('pageError', { type: 'error403' });
      break;
    case 400:
      goPage('pageError', { type: 'error500' });
      break;
    case 500:
      if (type === 'modal') {
        showMsg('error', msg);
      } else {
        goPage('pageError', { type: 'error500' });
      }
      break;
    case 7001:
      goPage('lock');
      break;
    case -500:
      break;
    default:
      showMsg('error', '请检查网络设置或联系技术人员');
  }
}
// 页面跳转
function goPage(name, query = {}) {
  let from = router.history.current.path;
  query.redirect = from;
  router.push({
    name,
    query
  });
}

// 获取数据特殊符号反转义
let transferred = {
  '*': /&#42;/g,
  '$': /&#36;/g,
  '%': /&#37;/g,
  '@': /&#64;/g,
  '\'': /&#39;/g,
  '<': /&lt;/g,
  '>': /&gt;/g,
  '(': /&#40;/g,
  ')': /&#41;/g,
  '+': /&#43;/g,
  ',': /&#44;/g,
  '\\"': /&guot;/g,
  '&': /&amp;/g // 一定在最后
};
function transferredJSON(json) {
  let r = JSON.stringify(json);
  for (let i in transferred) {
    r = r.replace(transferred[i], i);
  }
  return JSON.parse(r);
}

// Loading控制
let load = null;

function makeLoading(params) {
  // if (load !== null) { load.close(); }
  // if (params.dom !== undefined) {
  //   load = Loading.service({
  //     target: params.dom,
  //     fullscreen: true,
  //     lock: true,
  //     // text: '加载中...',
  //     spinner: 'el-icon-loading',
  //     background: 'rgba(0,0,0,0.2)'
  //   });
  // } else if (typeof params.loadTarget === 'string') {
  //   let dom = document.querySelector(params.loadTarget);
  //   if (dom !== null) {
  //     load = Loading.service({
  //       target: dom,
  //       lock: true,
  //       spinner: 'el-icon-loading',
  //       background: 'rgba(0,0,0,0.2)'
  //     });
  //   }
  // }
  // delete params.dom;
  // delete params.loadTarget;
  // return load;
}

function closeLoading() {
  setTimeout(() => {
    if (load !== null) { load.close(); }
  }, 0);
}

// axios请求配置
let axiosConfig = {
  transferred: false, // 不需要转码
  timeout: 30000
};
// axios.defaults.baseURL = process.env.PROXY ? '/' : process.env.BASE_API;
axios.defaults.baseURL = '/';
axios.defaults.withCredentials = true;

axios.defaults.timeout = axiosConfig.timeout;

let pending = {};
let CancelToken = axios.CancelToken;
let cancel;
console.log(cancel);
const whiteList = [
  '/common/dictionary/getDictionariesByType'
];

let removePending = config => {
  let pass = whiteList.filter(item => {
    return config.url.indexOf(item) != -1;
  });
  if ((!pass.length) && pending[config.url]) {
    pending[config.url]('repeat request!');
    pending[config.url] = false;
  } else {
    pending[config.url] = false;
  }
  // for (let p in pending) {
  //   console.log(config);
  //   if (pending[p].u === config.url + '&' + config.method) { // 当当前请求在数组中存在时执行函数体
  //     pending[p].f('asdfasdf'); // 执行取消操作
  //     pending.splice(p, 1); // 把这条记录从数组中移除
  //   }
  // }
};

// 请求拦截器
axios.interceptors.request.use(function(config) {
  removePending(config); // 在一个ajax发送请求前执行以下取消操作
  config.cancelToken = new CancelToken(c => {
    // pending.push({ u: config.url + '&' + config.method, f: c });
    pending[config.url] = c;
  });
  // config.headers['Host'] = 'investor.shch.local';
  // config.headers['Referer'] = 'https://investor.shch.local';
  // config.headers['Origin'] = 'https://investor.shch.local';
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器及异常处理
axios.interceptors.response.use(response => {
  const res = {code: response.status, message: response.statusText, data: response.data};
  return res;
}, error => {
  let err = {};
  if (error.response != undefined) { // 有返回值
    let res = error.response;
    let data = res.data || {};
    let status = data.code || res.status || -1;
    err = {
      code: status,
      message: res.data.message || res.statusText,
      data: res.data
    };
    closeLoading();
  } else if (error.message === 'repeat request!') { // 重复请求
    err = { code: -500, message: '请求重复（不弹框）' };
  } else {
    closeLoading();
    showMsg('error', '请求异常');
    err = { code: -1, message: '请求异常' };
  }
  errorSwich(err);
  return Promise.reject(err);
});
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; // 配置请求头
// axios.defaults.transformRequest = [function (data) {
//   return typeof data === 'object' && String(data) !== '[object File]' ? toFormData(data) : data;
// }];

/**
 * @param string method: 请求类型，get/post/put/delete/patch
 * @param Object configs: 请求参数，可传入特殊字段如下下：
 * loading： true 可在请求成功后关闭loading遮罩
 * isCheckLoading：true 校验类请求，仅在发生错误时关闭loading遮罩
 * hasMessage： true 请求后message弹框 | false 不提示信息 | null 仅错误时提示信息
 * successCallbackWaitTimeBySecond: 成功回调函数延时（秒），默认0
 * @param Object json_param: 以json形式传参（get无效）
 * @param Object form_param: 以地址形式传参
 * */
let $http = function(method, url, {json_param={}, url_param={}, configs={}}, successCallback, errorCallback) {
  url_param['random'] = Math.floor(Math.random() * (100000 + 1));
  url += '?' + toFormData(url_param);
  return new Promise(function(resolve, reject) {
    axios({
      method,
      url,
      // param: form_param,
      data: json_param, // json参数
      cancelToken: new CancelToken(function executor(c) {
        // 一个执行器函数接受一个取消函数作为函数
        cancel = c;
      }),
      timeout: configs.timeout || axiosConfig.timeout,
      // proxy: {
      //   host: '127.0.0.1',
      //   port: 5000,
      //   auth: {
      //     // username: 'mikeymike',
      //     // password: 'rapunz3l'
      //   }
      // },
      // headers: {'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'},
      // withCredentials: true,
      // 格式化发送数据
      // transformRequest: [function(data) {
      //   return typeof data === 'object' && String(data) !== '[object File]' ? toFormData(data) : data;
      // }]
    }).then(function(res) {
      // 如有需要转码 返回数据转码
      // let data = axiosConfig.transferred ?
      //   transferredJSON(res.data) : res.data;
      return res.data;
    }).then(function(res) {
      resolve(res);
      if (configs.isMessage) {
        // 弹出成功请求 data.message
      }
      if (successCallback && successCallback instanceof Function) {
        successCallback(res);
      }
    }, function(err) {
      if (errorCallback && errorCallback instanceof Function) {
        errorCallback(err);
      }
      return err;
    });
  });
}
Vue.prototype.$http = $http;

//文件下载 动态生成表单 post formdata传参
Vue.prototype.downloadFile1 = function(exportUrl,param, hasEn, option) {
  option = option || {
    clientType: 'manager' // 系统类型 默认后台，前台client
  };
  var content = "生成文件需要花费几分钟，请耐心等待";
  if(option.clientType === "client") {
    content = "正在生成下载文件，请稍后..." + (!hasEn ? "" : "<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
  }

  var content = "生成文件需要花费几分钟，请耐心等待" + (!hasEn ? "" : "<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
  layer.msg(content);
  // if(hasEn || hasEn === false) {
  //     layer.msg(content);
  // }
  if ($('#iframe').length > 0) {
    $('#iframe').remove();
  }
  var arr = [];
  arr.push('<div id="iframe" style="display:none;"><iframe id="exportIframe" width="0" height="0"></iframe>');

  var formData = '<form method="post" action='+exportUrl+' >';
  if(param) {
    for(var i in param){
      formData += '<input type="input" name="'+ i + '" value="' + param[i] + '"/>';
    }
  }

  formData = formData + '<input type="submit" id="submitExportForm"/>';
  formData = formData + '</form>';
  arr.push(formData);

  arr.push('</div>');
  $('body').append(arr.join(''));
  $('#submitExportForm').click();
};

Vue.prototype.upload = function(url, params, successCallback, errorCallback) {
  var forms = new FormData();
  for (let i in params) {
    forms.append(i, params[i]);
  }
  return new Promise(function(resolve, reject) {
    axios.post(url, forms, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 3600000
    }).then(function(res) {
      return res;
    }).then(function(res) {
      resolve(res.data);
      if (params.isMessage) {
        showMsg('success', res.data.message);
      }
      if (successCallback && successCallback instanceof Function) {
        successCallback(res.data);
      }
    }, function(err) {
      if (errorCallback && errorCallback instanceof Function) {
        errorCallback(err);
      }
      return err;
    });
  });
};

Vue.prototype.getImg = function(url, params, successCallback, errorCallback) {
  return new Promise(function(resolve, reject) {
    axios.get(url, {
      params: params,
      responseType: 'arraybuffer'
    }).then(function(res) {
      return 'data:image/png;base64,' + btoa(
        new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
      );
    }).then(function(data) {
      resolve(data);
      if (params.isMessage) {
        showMsg('success', '获取图片失败');
      }
      if (successCallback && successCallback instanceof Function) {
        successCallback(data);
      }
    }, function(err) {
      if (errorCallback && errorCallback instanceof Function) {
        errorCallback(err);
      }
      return err;
    });
  });
};

// 注销
function logout() {
  let u = store.getters.getUserInfo;
  if (JSON.stringify(u) === '{}' || u == null || u == undefined) {
    store.commit('setUserInfo', {});
    goPage('login');
  } else {
    get('/manager/logout', {}, function() {
      goPage('login');
    }, function() {
      goPage('login');
      // showMsg('error', '注销失败');
    });
  }
}
Vue.prototype.logout = logout;
export {
  logout,
  get
};
